# -*- coding: utf-8 -*-
import json
import requests
import os
import signal
import time
import serial
import threading
import base64
import redis

time.sleep(6)
def signal_handler(signal, frame):

    print('program exit')
    try:
        ser.close()
        gpsfile.close()
    except:
        pass
    exit()
signal.signal(signal.SIGINT, signal_handler)

errlog = "/home/wwwroot/pavgps/errlog.log"
file1 = "/home/wwwroot/pavgps/config.json"
global conf

if os.path.isfile(file1)==True:

    f=open(file1)
    s=f.read()
    conf= json.loads(s)

    for n in conf:
        if type(conf[n])==int:
            continue
        conf[n] = conf[n].strip()

    if ('rtkserver' in conf.keys())==False:
        print('not set rtkserver')
        exit()
    elif ('gpsserver' in conf.keys())==False:
        print('not set gpsserver')
        exit()
    elif conf['gpsserver'].find('zjzd-tech.com')==-1:
        print('gpsserver addr err')
        exit()
    elif ('sid' in conf.keys())==False:
        print('not set sid')
        exit()
    elif ('GpsSerialPort' in conf.keys())==False or conf['GpsSerialPort']=='':
        print('not set GpsSerialPort')
        exit()
    elif ('GpsBaudRate' in conf.keys())==False:
        print('not set GpsBaudRate')
        exit()

    if conf['GpsBaudRate']=='':
        conf['baudRate']=9600
else:
    print("not find config file")
    quit()

url = 'http://'+conf['rtkserver']

def getRtkData(conf):
    ser2=None
    while True:
        time.sleep(2)
        print('run loop')
        try:
            redis_remote = redis.StrictRedis(host='base.zjzd-tech.com',port=6888,password='zjzd')
            ps = redis_remote.pubsub()
            ps.subscribe('RTK_'+conf['rtkserver'])
            print('########RTK:RTK_'+conf['rtkserver'])
        except:
             print('reConnect Err')
             pass

        try:
            for data in ps.listen():
                # print(data['data'])
                if ser2==None:
                    try:
                        ser2=serial.Serial(conf['GpsSerialPort'],conf['GpsBaudRate'],timeout=0.5)
                        print( time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ,  'gps serail open success')
                    except :
                        print('not open gps serialPort')
                        time.sleep(3)
                else:
                    if data['type']=='message':
                        # print(data["data"])
                        rawdata = base64.b64decode(data["data"])
                        ser2.write(rawdata)
        except Exception as e:
            print('reConnntectingRTK...')


def getTemp(ser):
    temp = 0
    if ser!=None:
        ser.write("?T\r\n".encode())
        tmp = ser.readline().decode()
        if tmp.find('T') >0:
            temp = float(tmp[2:])
    return temp

def main_handle(conf):
    ser=None;
    #print("参数设置：串口=%s ，波特率=%d"%(conf['serialPort'],conf['baudRate']))
    print('main start..')
    # gpsfile=open('gps.txt','a')

    msg={}
    while 1:

        if ser==None:
            try:
                ser=serial.Serial(conf['GpsSerialPort'],conf['GpsBaudRate'],timeout=0.5)
                print( time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ,  'gps serail open success')
            except :
                print('not open gps serialPort')
                time.sleep(3)
        else:

            try:

                data = ser.readline()
                sdata = data.decode('utf-8')
                redisc.lpush('gpsdata',sdata)
                print(sdata)

            except  Exception as e:
                print(e)
                pass


        #time.sleep(1)
    ser.close()


if __name__=='__main__':
    redisc = redis.Redis(host='127.0.0.1',port=6379)
    threads = []
    conf["redisc"]=redisc

    t1 = threading.Thread(target=main_handle,args=(conf,))
    threads.append(t1)
    # t2 = threading.Thread(target=dhandler.upload_data, args=(conf,))
    # threads.append(t2)
    # t3 = threading.Thread(target=dhandler.download_data,args=(conf,))
    # threads.append(t3)
    t4 = threading.Thread(target=getRtkData,args=(conf,))
    threads.append(t4)

    for t in threads:
        t.setDaemon(True)
        t.start()

    while True:
        time.sleep(10)
        if redisc.get('RTK')==None:
            print("********* RTK Restart ************\r\n")
            os.system("ps aux | grep getrtk.py | awk '{print $2}'| xargs sudo kill")
            time.sleep(1)
            os.system("nohup python /home/wwwroot/pavgps/getrtk.py >/dev/null &")
        print('*********** ',time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))